package com.winai.launcher.BroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.FileUtils;
import com.yaoxiaowen.download.DownloadConstant;
import com.yaoxiaowen.download.DownloadHelper;
import com.yaoxiaowen.download.DownloadStatus;
import com.yaoxiaowen.download.FileInfo;

import java.io.File;

/**
 * 作者：康少
 * 时间：2020/4/10 0010
 * 说明：版本更新广播
 */
public class DownloadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null != intent) {
            FileInfo firstFileInfo = (FileInfo) intent.getSerializableExtra(DownloadConstant.EXTRA_INTENT_DOWNLOAD);
            if (firstFileInfo == null) {
                return;
            }
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            String downloadUrl = firstFileInfo.getDownloadUrl();
            if (action.equals(downloadUrl)) {
                int downloadStatus = firstFileInfo.getDownloadStatus();
                float pro = (float) (firstFileInfo.getDownloadLocation() * 1.0 / firstFileInfo.getSize());
                int progress = (int) (pro * 100);
                //下载完成
                switch (downloadStatus) {
                    case DownloadStatus.LOADING:
                        LogUtils.d("下载中：downloadUrl = " + downloadUrl + "，进度 = " + "( " + progress + " %)");
                    case DownloadStatus.COMPLETE:
                        if (progress < 100) {
                            return;
                        }
                        LogUtils.d("下载完成：downloadUrl = " + downloadUrl);
                        FileUtils.renameDownloadPath(downloadUrl);
                        // 下载完成回调
                        GlobalPublisher.Notify(GlobalPublisher.DOWNLOAD_ROM_COMPLETE, downloadUrl);
                        break;
                    case DownloadStatus.FAIL:
                        LogUtils.d("下载失败");
                        String currentTime = BaseUtils.getInitTime();
                        String hh = BaseUtils.timeStamp2Date(currentTime, "HH");
                        int currentHours = Integer.parseInt(hh);
                        //TODO 正式版本放开注释
                        if (currentHours >= 3 && currentHours <= 5) {
                            LogUtils.d("重新开启下载：url = " + downloadUrl);
                            DownloadHelper.getInstance()
                                    .addTask(downloadUrl, new File(FileUtils.getDownloadPath(downloadUrl)), downloadUrl)
                                    .submit(context);
                        }
                        break;
                }
            }
        }
    }
}
